package com.zjitc.pigspring.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.zjitc.pigspring.bean.dto.Account;
import com.zjitc.pigspring.bean.dto.VerCode;
import com.zjitc.pigspring.bean.po.Seller;
import com.zjitc.pigspring.bean.po.Admin;
import com.zjitc.pigspring.bean.po.User;
import com.zjitc.pigspring.common.Codes;
import com.zjitc.pigspring.common.Result;
import com.zjitc.pigspring.exception.ServiceException;
import com.zjitc.pigspring.service.SellerService;
import com.zjitc.pigspring.service.AdminService;
import com.zjitc.pigspring.service.UserService;
import com.zjitc.pigspring.utils.MD5Util;
import com.zjitc.pigspring.utils.RedisUtil;
import com.zjitc.pigspring.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;


@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/web")
public class WebController {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AdminService adminService;

    @Autowired
    private SellerService sellerService;

    @Autowired
    private UserService userService;

    @Autowired
    private MD5Util md5Util;

    /**
     * 登录
     * @param
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody Account account){

        String verCode = (String) redisUtil.get(account.getKey());
        if (!account.getCode().equals(verCode)){
            return Result.error(Codes.CODE_FAIL);
        }

        if(account.getRole().equals(Codes.SELLER)){
            QueryWrapper<Seller> wrapper = new QueryWrapper<Seller>()
                    .eq("username",account.getUsername());
            Seller dbseller = sellerService.getOne(wrapper);
            if(dbseller==null || !md5Util.hashPassword(account.getPassword()).equals(dbseller.getPassword())){
                return Result.error(Codes.NAME_OR_PASSWORD_FIELD);
            }
            if(!account.getRole().equals(dbseller.getRole())){
                return Result.error(Codes.ROLE_FIELD);
            }
            dbseller.setToken(TokenUtil.getToken(dbseller.getId(),dbseller.getRole()));
            return Result.success(dbseller,Codes.LOGIN_YES);
        }else if(account.getRole().equals(Codes.ADMIN)){
            QueryWrapper<Admin> wrapper = new QueryWrapper<Admin>()
                    .eq("username",account.getUsername());
            Admin dbadmin = adminService.getOne(wrapper);
            if(dbadmin==null||!md5Util.hashPassword(account.getPassword()).equals(dbadmin.getPassword())){
                return Result.error(Codes.NAME_OR_PASSWORD_FIELD);
            }
            if(!account.getRole().equals(Codes.ADMIN)){
                return Result.error(Codes.ROLE_FIELD);
            }
            dbadmin.setToken(TokenUtil.getToken(dbadmin.getId(),Codes.ADMIN));
            return Result.success(dbadmin,Codes.LOGIN_YES);
        }else{
            QueryWrapper<User> wrapper = new QueryWrapper<User>()
                    .eq("username",account.getUsername());
            User dbuser = userService.getOne(wrapper);
            if(dbuser==null||!md5Util.hashPassword(account.getPassword()).equals(dbuser.getPassword())){
                return Result.error(Codes.NAME_OR_PASSWORD_FIELD);
            }
            if (!account.getRole().equals(dbuser.getRole())){
                log.info("accountRole:{}",account);
                log.info("dbuserRole:{}",dbuser);
                return Result.error(Codes.ROLE_FIELD);
            }
            dbuser.setToken(TokenUtil.getToken(dbuser.getId(),dbuser.getRole()));
            return Result.success(dbuser,Codes.LOGIN_YES);
        }
    }

    /**
     * 注册
     * @param
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody Account account){
        if(account.getRole().equals("user")){
            QueryWrapper<User> wrapper = new QueryWrapper<User>()
                    .eq("username",account.getUsername());
            User dbuser = userService.getOne(wrapper);
            if(dbuser!=null){
                throw new ServiceException(Codes.USER_EXISTS);
            }
            User user = new User();
            user.setUsername(account.getUsername());
            user.setPassword(account.getPassword());
            boolean save = userService.save(user);
            if (save){
                return Result.success(Codes.REGISTER_SUCCESS);
            }else{
                return Result.error(Codes.REGISTER_FIELD);
            }
        }else if(account.getRole().equals("seller")){
            QueryWrapper<Seller> wrapper = new QueryWrapper<Seller>()
                    .eq("username",account.getUsername());
            Seller dbSeller = sellerService.getOne(wrapper);
            if (dbSeller!=null){
                throw new ServiceException(Codes.USER_EXISTS);
            }
            Seller seller = new Seller();
            seller.setUsername(account.getUsername());
            seller.setPassword(account.getPassword());
            boolean save = sellerService.save(seller);
            if (save){
                return Result.success(Codes.REGISTER_SUCCESS);
            }else{
                return Result.error(Codes.REGISTER_FIELD);
            }
        }else{
            return Result.error(Codes.REGISTER_FIELD);
        }
    }

    @GetMapping("/captcha")
    public Result<VerCode> getVerCode(){
        SpecCaptcha captcha = new SpecCaptcha(80,30,4);
        String code = captcha.text().toLowerCase();
        String key = UUID.randomUUID().toString();
        redisUtil.set(key,code,60*3);
        return Result.success(new VerCode(key,captcha.toBase64()));
    }
}
